<script setup>
import PageContainer from '@/components/PageContainer.vue';
import { ref } from 'vue';
import { useUserStore } from '@/stores';
import { userUpdataPasswordService } from '@/api/user';
const pwdForm = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})
const formRef = ref(null)
const onsubmit = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      await userUpdataPasswordService(pwdForm.value)
      ElMessage.success('修改成功')
    }
  })
}
// 三、校验需求
// 所有字段，都是 6-15位 非空
// 自定义校验1：原密码 和 新密码不能一样
// 自定义校验2：新密码 和 确认密码必须一样
const checkOldSame = (rule, value, cb) => {
  if (value === pwdForm.value.old_pwd) {
    cb(new Error('原密码和新密码不能一样!'))
  } else {
    cb()
  }
}
const checkNewSame = (rule, value, cb) => {
  if (value !== pwdForm.value.new_pwd) {
    cb(new Error('新密码和确认再次输入的新密码不一样!'))
  } else {
    cb()
  }
}
const rules = {
  // 原密码
  old_pwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码长度必须是6-15位的非空字符串',
      trigger: 'blur'
    }
  ],
  // 新密码
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码长度必须是6-15位的非空字符串',
      trigger: 'blur'
    },
    { validator: checkOldSame, trigger: 'blur' }
  ],
  // 确认新密码
  re_pwd: [
    { required: true, message: '请再次确认新密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码长度必须是6-15位的非空字符串',
      trigger: 'blur'
    },
    { validator: checkNewSame, trigger: 'blur' }
  ]
}

</script>

<template>
  <page-container title="重置密码">
    <template #main>
      <el-form ref="formRef" :rules="rules" label-width="100px" size="large" :model="pwdForm">
        <el-form-item label="原密码">
          <el-input v-model="pwdForm.old_pwd" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="pwdForm.new_pwd" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="pwdForm.re_pwd" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onsubmit">提交修改</el-button>
        </el-form-item>
      </el-form>
    </template>
  </page-container>
</template>
